package com.example.app2;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.app2.database.LoginHelper;
import com.example.app2.pojo.Login_Info;

import java.util.Random;
//优化了记住密码的逻辑，每次登录将上一次记住密码的用户的账号和密码自动填充。如果在数据库中有和用户填写的手机号相同的而且上次选了记住密码，也会自动填充密码
public class LoginDataBaseActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, View.OnFocusChangeListener {

    private TextView tv_password;
    private Button btn_forget;
    private EditText et_phone;
    private EditText et_password;
    private CheckBox ckb_remember;
    private Button btn_login;
    private RadioButton rb_password;
    private RadioButton rb_code;
    private ActivityResultLauncher<Intent> register;
    private String verifyCode;
    private String rightPassword="123456";
    private SharedPreferences config;
    private LoginHelper mHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logindatabase);
        RadioGroup rg_login_method = findViewById(R.id.rg_login_method);
        tv_password = findViewById(R.id.tv_password);
        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.et_password);
        btn_forget = findViewById(R.id.btn_forget_password);
        ckb_remember = findViewById(R.id.ckbr_remember);
        btn_login = findViewById(R.id.btn_login);
        rg_login_method.setOnCheckedChangeListener(this);
        rb_password = findViewById(R.id.rb_password);
        rb_code = findViewById(R.id.rb_code);
        btn_forget.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        et_phone.setOnFocusChangeListener(this);
        et_password.setOnFocusChangeListener(this);
        et_password.addTextChangedListener(new HideKeyBoardTextWatcher(et_password,6));
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if(result!=null)
                {
                    Intent intent=result.getData();
                    if(intent!=null&&result.getResultCode()==RESULT_OK)
                    {
                        Bundle bundle = intent.getExtras();
                        String password = bundle.getString("password");
                        et_password.setText(password);
                        Toast.makeText(LoginDataBaseActivity.this, "找回密码成功", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
        mHelper=LoginHelper.getInstance(this);
        mHelper.openReadLink();
        mHelper.openWriteLink();
        load();
    }
    public void load()
    {
        //获取数据库中上一个记住密码的用户，并自动填充进账号和密码中
        Login_Info info = mHelper.queryLastChecked();
        if(info!=null)
        {
            et_phone.setText(info.phone);
            et_password.setText(info.password);
            ckb_remember.setChecked(false);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {
        super.onStop();
        mHelper.closeLink();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId)
        {
            case R.id.rb_password:
                //改变布局
                tv_password.setText("登录密码:");
                et_password.setHint("请输入密码");
                btn_forget.setText("忘记密码");
                ckb_remember.setVisibility(View.VISIBLE);
                break;
            case R.id.rb_code:
                //改变布局
                tv_password.setText("    验证码:");
                btn_forget.setText("发送验证码");
                et_password.setHint("请输入验证码");
                ckb_remember.setVisibility(View.INVISIBLE);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        String phone = et_phone.getText().toString();
        String password=et_password.getText().toString();

        switch (v.getId())
        {
            case R.id.btn_forget_password:
                if(rb_password.isChecked())
                {
                    //跳到新界面找回
                    Intent intent=new Intent(LoginDataBaseActivity.this,FindBackPasswordActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("phone",phone);
                    intent.putExtras(bundle);
                    register.launch(intent);
                }
                else if(rb_code.isChecked())
                {
                    //生成6位随机验证码
                    verifyCode = String.format("%06d",new Random().nextInt(999999));
                    //跳出一个验证码对话框
                    AlertDialog.Builder builder=new AlertDialog.Builder(this);
                    builder.setTitle("请记住验证码");
                    builder.setMessage("手机号："+phone+",本次验证码为："+ verifyCode);
                    builder.setPositiveButton("确认", null);
                    AlertDialog dialog=builder.create();
                    dialog.show();
                }
                break;
            case R.id.btn_login:
                //验证账号和密码或者验证码是否合法
                if(rb_password.isChecked())
                {
                    if(rightPassword.equals(password))
                    {
                        loginSuccess();
                    }
                    else {
                        Toast.makeText(this, "账号或密码错误，请重新输入", Toast.LENGTH_SHORT).show();
                    }
                } else if (rb_code.isChecked()) {
                    if (verifyCode!=null&&verifyCode.equals(password)) {
                        loginSuccess();
                    }
                    else
                    {
                        Toast.makeText(this, "验证码错误，登录失败", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    private void loginSuccess() {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("登录成功");
        builder.setMessage("是否结束登录");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();//结束本窗口
            }
        });
        builder.setNegativeButton("我再看看",null);
        AlertDialog dialog = builder.create();
        dialog.show();
        Login_Info info = new Login_Info(et_phone.getText().toString(), et_password.getText().toString(),ckb_remember.isChecked());

        try {
            mHelper.WStartTrans();
            mHelper.deleteByPhone(info.phone);
            mHelper.insert(info);
            mHelper.WTransSuccessful();
        }catch (Exception e)
        {
            e.printStackTrace();
        }finally {
            mHelper.WEndTrans();
        }
    }
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(v.getId()==R.id.et_password&&hasFocus)
        {
            if(et_phone.getText().toString().length()<11)
            {
                Toast.makeText(this, "请输入11位手机号码", Toast.LENGTH_SHORT).show();
                return;
            }
            Login_Info info = mHelper.queryByPhone(et_phone.getText().toString());
            if(info!=null)
            {
                et_password.setText(info.password);
            }
        }
    }

    private class HideKeyBoardTextWatcher implements TextWatcher {
        int num;
        EditText et;
        HideKeyBoardTextWatcher(EditText et,int num)
        {
            this.et=et;
            this.num=num;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            //隐藏键盘
            if (num==s.toString().length())
            {
                InputMethodManager imm= (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et.getWindowToken(),0);
                et.requestFocus();
            }
        }
    }
}
